//
//  PicCollectionView.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/6/6.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
import SDWebImage
class PicCollectionView: UICollectionView {
//    MARK:- 约束属性
    @IBOutlet weak var collectionViewWidthCons: NSLayoutConstraint!
    @IBOutlet weak var collectionViewHeightCons: NSLayoutConstraint!
    var picURLs : [NSURL] = [NSURL](){
        didSet{
//          1.设置collectionView的宽度和高度
            let (width,height) = calculatePicCollectionSize(picURLs.count)
            collectionViewWidthCons.constant = width
            collectionViewHeightCons.constant = height
//          2.更新数据
            reloadData()
        }
    }
//    MARK:- 系统回调函数
    override func awakeFromNib() {
        super.awakeFromNib()
        dataSource = self
        delegate = self
        
        // 设置布局
//        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
//        let imageWH = (UIScreen.mainScreen().bounds.width - 2 * edgeMargin - 2 * padding) / 3
//        layout.itemSize = CGSize(width: imageWH, height: imageWH)
//        layout.minimumInteritemSpacing = padding
//        layout.minimumLineSpacing = padding

    }
}
// MARK:- 计算PicCollectionView的高度
extension PicCollectionView{
    func calculatePicCollectionSize(count : Int) -> (CGFloat,CGFloat) {
        //        如果没有图片
        if count == 0 {
            return(0,0)
        }
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        if count == 1 {
            let urlString = picURLs.first?.absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
            let width = image.size.width * 3
            let height = image.size.height * 3
            layout.itemSize = CGSizeMake(width, height)
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            return (width, height)
        }
        //        计算图片的宽度和高度
        let imageWH = (UIScreen.mainScreen().bounds.width - 2 * edgeMargin - 2 * padding) / 3
        layout.itemSize = CGSize(width: imageWH, height: imageWH)
        layout.minimumInteritemSpacing = padding
        layout.minimumLineSpacing = padding

        //        只有四张图片
        if count == 4 {
            let width = 2 * imageWH + padding
            let height = 2 * imageWH + padding
            return (width + 1,height)
        }
        //        其他张数的图片计算
        let row = CGFloat((count - 1)/3 + 1)
        let width = 3 * imageWH + 2 * padding
        let height = row * imageWH + (row - 1 ) * padding
        return (width,height)
    }
   
}
// MARK:- 数据源代理方法
extension PicCollectionView : UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PicViewCellID", forIndexPath: indexPath) as! PicCollectionViewCell
        cell.picURL = picURLs[indexPath.item]
        return cell
    }
}
//MARK:- 实现代理方法
extension PicCollectionView : UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let userInfo = [showPhotoBrowserVcNoteIndex:indexPath,showPhotoBrowserVcNotePicURLs:picURLs]
        NSNotificationCenter.defaultCenter().postNotificationName(showPhotoBrowserVcNote, object: self, userInfo: userInfo)
    }
}
extension PicCollectionView:PhotoBrowserPresentedDelegate{
    func startRectForPresentedView(indexPath: NSIndexPath) -> CGRect {
//        取出cell
        let cell = cellForItemAtIndexPath(indexPath)!
//        计算出cell在window中的位置
        let rect = convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return rect
    }
    func endRectForPresentedView(indexPath: NSIndexPath) -> CGRect {
//        取出picURL
        let picURL = picURLs[indexPath.item]
//        通过picURL取出图片
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(picURL.absoluteString)
//        计算图片方法后的位置
        let x : CGFloat = 0
        let width = UIScreen.mainScreen().bounds.width
        let height = UIScreen.mainScreen().bounds.width / image.size.width * image.size.height
        var y = (UIScreen.mainScreen().bounds.height - height) * 0.5
        y = y < 0 ? 0 : y
        let rect : CGRect = CGRect(x: x, y: y, width: width, height: height)
        return rect
    }
    func imageViewForPresentedView(indexPath: NSIndexPath) -> UIImageView {
//        创建imageView 
        let imageView = UIImageView()
//        取出picURL
        let picURL = picURLs[indexPath.item]
//        取出图片需要显示的图片
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(picURL.absoluteString)
        imageView.image = image
//        设置imageView的属性
        imageView.clipsToBounds = true
        imageView.contentMode = .ScaleAspectFill
        return imageView
    }
}
// MARK:- 自定义PicCollectionViewCell
class PicCollectionViewCell: UICollectionViewCell {
    var picURL : NSURL?{
        didSet{
            picImageView.sd_setImageWithURL(picURL, placeholderImage: UIImage(named: "empty_picture"))
        }
    }
//    MARK:- 控件属性
    @IBOutlet weak var picImageView: UIImageView!
}